<template>
    <el-drawer v-model="drawer" title="用户信息填写" direction="rtl" :before-close="handleClose" size="575">
        <el-form label-width="auto" :model="addItem" ref="ruleFormRef" :rules="rules">
            <el-form-item label="真实姓名:" label-width="100px" prop="name">
                <el-input placeholder="请输入真实姓名" style="width: 400px;" v-model="addItem.name" />
            </el-form-item>
            <el-form-item label="手机号：" label-width="100px" prop="phone">
                <el-input placeholder="请输入真实姓名" style="width: 400px;" v-model="addItem.phone" />
            </el-form-item>
            <el-form-item label="生日:" label-width="100px">
                <el-col :span="11">
                    <el-date-picker type="date" placeholder="Pick a date" style="width: 100%" v-model="addItem.birth" />
                </el-col>
            </el-form-item>
            <el-form-item label="身份证号：" label-width="100px">
                <el-input placeholder="请输入身份证号" style="width: 400px;" v-model="addItem.IDNumber" />
            </el-form-item>
            <el-form-item label="用户地址：" label-width="100px">
                <el-input placeholder="请输入用户地址" style="width: 400px;" v-model="addItem.address" />
            </el-form-item>
            <el-form-item label="用户备注：" label-width="100px">
                <el-input placeholder="请输入用户备注" style="width: 400px;" v-model="addItem.remark" />
            </el-form-item>
            <el-form-item label="登陆密码：" label-width="100px" prop="password">
                <el-input placeholder="请输入登陆密码" style="width: 400px;" v-model="addItem.password" type="password" />
            </el-form-item>
            <el-form-item label="确认密码：" label-width="100px" prop="checkPassword">
                <el-input placeholder="请输入确认密码" style="width: 400px;" v-model="checkPassword" type="password" />
            </el-form-item>
            <el-form-item label="用户等级：" label-width="100px">
                <el-select placeholder="请选择用户等级" style="width: 400px;" v-model="addItem.gradeId" clearable>
                    <el-option v-for="item in userLevelData.rows" :key="item._id" :label="item.name"
                        :value="item._id as string" />
                </el-select>
            </el-form-item>
            <el-form-item label="用户分组：" label-width="100px">
                <el-select placeholder="请选择用户分组" style="width: 400px;" v-model="addItem.groupId" clearable>
                    <el-option v-for="item in userGroupData.rows" :key="item._id" :label="item.name"
                        :value="item._id as string" />
                </el-select>
            </el-form-item>
            <el-form-item label="用户标签：" label-width="100px" >
                <el-input-tag v-model="checkedTagNames" style="width: 400px;" clearable
                    @click="userTagRef?.openUserTagDialog">
                </el-input-tag>
            </el-form-item>
            <el-form-item label="分销禁用：" label-width="100px">
                <el-radio-group v-model="addItem.sale_disabled">
                    <el-radio value="1">是</el-radio>
                    <el-radio value="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="分销权限：" label-width="100px">
                <el-radio-group v-model="addItem.sale_auth">
                    <el-radio value="1">开启</el-radio>
                    <el-radio value="0">关闭</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item>
                <div class="flex-ct" style="width: 100%;">
                    <el-button>
                        取消
                    </el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        提交
                    </el-button>
                </div>
            </el-form-item>
        </el-form>
        <UserTag ref="userTagRef" @getCheckedUserTag='getCheckedUserTag' />
    </el-drawer>

</template>

<script setup lang="ts">
import { onMounted, reactive, ref, useTemplateRef, watch } from 'vue'
import { ElMessageBox } from 'element-plus'
import { addUserListApi, } from '@/api/userList'
import type { FormInstance, FormRules } from 'element-plus'
import { useFindData } from '@/composables/findData'
import UserTag from './UserTag.vue'
const ruleFormRef = ref<FormInstance>();
const addItem = ref<any>({});
const checkPassword = ref('');
const userTagRef = useTemplateRef('userTagRef');
const checkedTagNames = ref<string[]>([]);
let checkedTagArray: any[] = [];
interface RuleForm {
    name: string,
    phone: string,
    password: string,
    checkPassword: string,
};
const { userLevelData, getUserLevelJoint,userGroupData, getUserGroupApiJoint, } = useFindData();
onMounted(() => { getUserLevelJoint();getUserGroupApiJoint(); });

const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '用户昵称不能为空', trigger: 'blur' },
        { min: 1, max: 5, message: '昵称长度不能超过8', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        {

            validator(_, value) {
                const phoneRegExp = /^1[3456789]\d{9}$/
                return phoneRegExp.test(value);
            },
            message: '手机号格式不正确',
            trigger: 'blur'
        },
    ],
    password: [
        { required: true, message: '登录密码不能为空', trigger: 'blur' },
        {

            validator(_, value) {
                const passwordRegExp = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{6,16}$/
                return passwordRegExp.test(value);
            },
            message: '密码格式不正确(6-16位字母和数字组合且以大写字母开头)',
            trigger: 'blur'
        },
    ],
    checkPassword: [
        {
            required: true,
            validator() {
                return (addItem.value.password == checkPassword.value ? true : false)
            },
            message: '两次密码不一致',
            trigger: 'blur'
        },
    ],
})
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            addUserList({ ...addItem.value });
        } else {
            console.log('error submit!', fields)
        }
    })
}


const drawer = ref(false)


const handleClose = (done: () => void) => {
    ElMessageBox.confirm('Are you sure you want to close this?')
        .then(() => {
            addItem.value = ref({});
            done();
        })
        .catch(() => {
            // catch error
        })
}


defineExpose({ openForm })

watch(checkedTagNames, () => {
    addItem.value.tagIds = checkedTagArray.filter(item => checkedTagNames.value.includes(item.name)).map(item => item._id)
}, { deep: true })

function openForm() {
    drawer.value = true;

}

function addUserList(data: any) {
    addUserListApi(data).then(res => {
        console.log(res);
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '添加用户成功',
            })
        } else {
            ElMessage.error(res.message);
        }

    })
}


function getCheckedUserTag(checkedTag: any[]) {
    checkedTagArray = checkedTag;
    addItem.value.tagIds = checkedTag.map(item => item._id);
    console.log(addItem.value.tagIds);
    
    console.log(checkedTag.map(item => item.name),checkedTagNames.value);
    
    checkedTagNames.value = checkedTag.map(item => item.name);
}
</script>

<style scoped>
.el-drawer__body {
    padding: 20px 35px;
}
</style>
<style>
.el-drawer__title,
.el-form-item__label {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
}

.el-form-item__content {
    width: 100% !important
}
</style>
